<template>
	<div class="pop zeal-chat">
		<div class="zeal-chat-contant" style="height: 500px">
			<section class="ui-container" ref="homePage">
				<ul class="chat-message">
					<li v-for="(chat, index) in messageData" :key="index" :class="chat.fromUser.id === agent.id ? 'an-move-right' : chat.label === 'system' ? '' : 'an-move-left'">
						<p class="time" v-show="chat.label === 'system'">
							<span>{{ getFormatTime(chat.date) }}</span>
						</p>
						<p class="time" v-show="chat.showTime && chat.label !== 'system'">
							<span>{{ getFormatTime(chat.date) }}</span>
						</p>

						<div class="system-msg" v-show="chat.label === 'system'">
							<span>{{ chat.data }}</span>
						</div>
						<div class="main">
							<chat-message :message="chat.data" :index="index" :user="chat.fromUser" :name="chat.fromUser.name" :msgType="chat.type" :mediaId="chat.clientId" :fileurl="chat.fileurl" :type="chat.label"></chat-message>
						</div>
					</li>
				</ul>
			</section>
		</div>
		<div class="line"></div>
		<div class="webeditor">
			<div class="tools"> </div>
			<div class="z_file" onclick="document.getElementById('imgfile').click()">
				<input style="display: none;" type="file" name="file" id="imgfile" value="" accept="image/gif,image/jpg,image/jpeg,image/png" @change="sendImage($event)" />
			</div>
			<div class="z_file2" onclick="document.getElementById('docfile').click()">
				<input style="display: none;" type="file" name="docfile" id="docfile" value="" @change="sendFile($event)" />
			</div>
			<div class="tool-div">
				<Dropdown @on-click="commonPhrases" class="self-dropdown">
					<Button type="primary" style="background:rgba(58,152,255,1);width: 70px;height: 30px">
						{{ $t('ivcs.normalword') }}
						<Icon type="ios-arrow-down"></Icon>
					</Button>
					<DropdownMenu slot="list">
						<DropdownItem v-for="(raw, index) in commonList" :name="raw.id" :key="index">{{ raw.value }}</DropdownItem>
					</DropdownMenu>
				</Dropdown>
				<Button @click="sendMessage(false)" type="primary" class="send-button" style="background:rgba(58,152,255,1);width: 50px;height: 30px">{{ $t('ivcs.send') }}</Button>
			</div>
			<div class="write_box">
				<div class="body" contenteditable="true" id="textView"></div>
			</div>
		</div>
		<div v-show="showImg" class="window-shadow"> </div>
		<div v-show="showImg" class="window-img">
			<img @click="closeFullImg" class="close" src="../../static/img/close.png" />
			<img src="" />
		</div>

		<message ref="message"></message>
	</div>
</template>

<script>
import ivcs from '../ivcs-sdk';
import ChatMessage from './ChatMessage';
import { dateStr } from '../tool/tool';
import imchat from '../tool/imchat';
import Message from './Message';
import { getsessiondetail } from '../api/api';
import { enterSendAndCtrlEnterNewLine } from '../tool/inputEnterCtrl';
import { sendMessageToRecord, formatMessageTime, filterAgentByMsg } from '../tool/util';
import { uploadFile } from '../tool/uploadFile';
import { mapMutations, mapState } from 'vuex';
export default {
	name: 'IM',
	components: { Message, ChatMessage },
	props: {
		agentId: {
			type: String,
			default: () => ''
		},
		sessionId: {
			type: String,
			default: () => ''
		}
	},
	data() {
		return {
			showImg: false,
			commonList: [
				{ id: '1', value: this.$t('ivcs.word1') },
				{ id: '2', value: this.$t('ivcs.word2') },
				{ id: '3', value: this.$t('ivcs.word3') },
				{ id: '4', value: this.$t('ivcs.word4') }
			],
			agentccsClient: null,
			ccsUrl: null,
			ticket: null,
			ccsinterval: null,
			chatList: this.$store.state.chatList,
			holdonmsgId: null,
			needLeave: false, //转接是否需要离开
			uploadurl: localStorage.getItem('uploadUrl'),
			startMsgTime: 0 // 首条非系统消息时间
		};
	},
	mounted() {
		var self = this;
		enterSendAndCtrlEnterNewLine('textView', function() {
			self.sendMessage();
		});
		this.initEmotion();
		imchat.$on('collectionPic', function(type) {
			self.sendTextMessageToCustomer('agentcollectionPic=' + type, 0);
		});
		imchat.$on('onShareResource', data => {
			this.onShareResource(data);
		});
		imchat.$on('onTextMessage', data => {
			this.onTextMessage(data);
		});
		imchat.$on('getSessionData', sessionId => {
			this.getSessionData(sessionId);
			console.log(sessionId);
		});
	},

	computed: {
		...mapState({
			messageData: state => state.message.messageData,
			customer: state => state.user.customer,
			agent: state => state.user.agent,
			sessionMembers: state => state.user.sessionMembers
		})
	},

	destroyed() {
		imchat.$off('collectionPic');
		imchat.$off('onShareResource');
		imchat.$off('onTextMessage');
		imchat.$off('getSessionData');
	},
	watch: {
		'$store.state.chatList'(newChatList) {
			this.chatList = newChatList;
		},
		'$store.state.message.messageData'(value, oldValue) {
			console.log('messageData,', value, oldValue);
			if (value && value.length > 0) {
				let index = value.length > 0 ? value.length - 1 : 0;
				//系统消息默认显示时间，其他消息计算时间
				if (value[index].label === 'system') {
					this.messageData[index].showTime = true;
				} else {
					this.setMsgTimer();
				}
			} else {
				this.startMsgTime = 0; //挂断后，数据清空为0
			}
		}
	},

	methods: {
		...mapMutations('message', ['SET_MESSAGE_DATA']),
		onShareResource(resp) {
			var self = this;
			let msg;
			let client = filterAgentByMsg(resp.from, this.sessionMembers);
			if (resp.data.type === 'pic') {
				//接收到照片
				self.$Message.success(self.$t('session.success'));
				msg = sendMessageToRecord('link', resp, client);
				this.setMsgTimer();
				self.scrollToBottom();
			} else if (resp.data.type === 'doc') {
				msg = sendMessageToRecord('link', resp, client);
				self.scrollToBottom();
			} else if (resp.data.type === 'video') {
				let message = '<a href="javascript:void(0)">' + resp.data.url;
				let result = {
					type: 'customer',
					date: dateStr(),
					message: message,
					msgType: 'file',
					fileurl: resp.data.url
				};
				const list = [...this.$store.state.chatList];
				this.$store.commit('setChatList', [...list, result]);
				self.scrollToBottom();
			}
			console.log(msg);
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
		},

		/**
		 * 接收到文字消息
		 */
		onTextMessage(resp) {
			var message = resp.data;
			var text = textFace2imgFace(message);
			var result = '';
			switch (text) {
				case 'silence-msg':
					result = '- -';
					break;
				case 'onTaskFailed':
					result = '- -';
					break;
				default:
					result = text;
					break;
			}

			let client = filterAgentByMsg(resp.from, this.sessionMembers);
			console.log('clientInfo:', client);
			let msg = sendMessageToRecord('text', result, client);
			this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
			this.setMsgTimer();
			this.scrollToBottom();
		},

		getSessionData(sessionId) {
			var self = this;
			getsessiondetail(sessionId)
				.then(function(resp) {
					if (resp.data.code === 200) {
						self.initSessionChatData(resp.data.data.recordList.data);
					}
				})
				.catch(function(error) {
					console.log(error);
				});
		},

		/*发文字消息*/
		sendMessage() {
			if (this.operatingJudgment() === 0) {
				return;
			}
			var text = $('.body').html();
			if (text == '') {
				this.$Message.error(this.$t('ivcs.messagenull'));
				$('.body').focus();
				return;
			}
			var content = imgFace2textFace(
				text
					.replace(/<br>/gi, '\n')
					.replace(/<div>/gi, '\n')
					.replace(/<(?!img|embed).*?>/gi, '')
					.replace(/&nbsp;/gi, ' ')
			);
			console.log('sendText:', content);
			console.log(this.sessionMembers);
			this.sendTextMessageToCustomer(content);
		},

		commonPhrases(value) {
			var message = '';
			if (value == 1) {
				message = this.commonList[0].value;
			} else if (value == 2) {
				message = this.commonList[1].value;
			} else if (value == 3) {
				message = this.commonList[2].value;
			} else if (value == 4) {
				message = this.commonList[3].value;
			}
			this.sendTextMessageToCustomer(message);
		},

		sendTextMessageToCustomer(message, needaddhistory) {
			if (this.operatingJudgment() === 0) {
				return;
			}
			let agents = this.sessionMembers.filter(item => item.role === 'agent');
			let role = agents.length > 1 ? 'others' : 'customers';
			ivcs.agent.sendTextMessage(
				message,
				role,
				resp => {
					console.log('send text message', resp);
					if (needaddhistory != 0) {
						let msg = sendMessageToRecord('text', textFace2imgFace(message), this.agent);
						this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
						this.setMsgTimer();
					}
					$('.body').html('');
					this.scrollToBottom();
				},
				error => {
					console.log('send text message error', error);
					this.$Message.error(error.message);
				}
			);
		},
		/*发文件*/
		async sendFile(event) {
			if (this.operatingJudgment() === 0) {
				return;
			}
			let file = document.getElementById('docfile').files[0];
			var fileSize = file.size;
			console.log('doc filesize', fileSize);
			if (fileSize > maxUploadFileSize) {
				this.$Message.error(this.$t('ivcs.exceedingTheSizeLimit'));
				event.target.value = null;
				return;
			}
			let data = await uploadFile(file);
			if (data) {
				this.sendResource('doc', data)
					.then(() => {
						this.$Message.success(this.$t('session.success'));
						let msgData = { data: { ...data, type: 'doc' } };
						let msg = sendMessageToRecord('link', msgData, this.agent);
						this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
						this.setMsgTimer();
						$('.body').html('');
						this.scrollToBottom();
					})
					.catch(error => {
						this.$Message.error(error);
						console.log('share resource failed', error);
					});
			} else {
				this.$Message.success(this.$t('session.failed'));
			}
			event.target.value = null;
		},
		/*发图片*/
		async sendImage(event) {
			if (this.operatingJudgment() === 0) {
				return;
			}
			var file = document.getElementById('imgfile').files[0];
			// 支持png jpg jpeg gif格式
			let imgTest = ['png', 'jpg', 'jpeg', 'gif'];
			let index = file.name.lastIndexOf('.');
			let ext = file.name.substr(index + 1).toLowerCase();
			if (imgTest.indexOf(ext) == -1) {
				this.$Message.error(this.$t('ivcs.imageSupportFormat'));
				return;
			}
			var fileSize = file.size;
			console.log('doc filesize', fileSize);
			if (fileSize > maxUploadFileSize) {
				this.$Message.error(this.$t('ivcs.exceedingTheSizeLimit'));
				event.target.value = null;
				return;
			}
			let data = await uploadFile(file);
			if (data) {
				this.sendResource('pic', data)
					.then(() => {
						this.$Message.success(this.$t('session.success'));
						let msgData = { data: { ...data, type: 'pic' } };
						let msg = sendMessageToRecord('link', msgData, this.agent);
						this.$store.commit('SET_MESSAGE_DATA', [...this.messageData, msg]);
						this.setMsgTimer();
						$('.body').html('');
						this.scrollToBottom();
					})
					.catch(error => {
						this.$Message.error(error);
						console.log('share resource failed', error);
					});
			} else {
				this.$Message.success(this.$t('session.failed'));
			}
			event.target.value = null;
		},

		operatingJudgment() {
			if (this.sessionId == null) {
				this.$Message.error(this.$t('ivcs.nosession'));
				return 0;
			}
			return 1;
		},

		/*UI滑动*/
		scrollToBottom() {
			var speak_height = $('.chat-message').height();
			speak_height = speak_height + 100;
			$('.ui-container,.zeal-chat-contant').animate(
				{
					scrollTop: speak_height
				},
				500
			);
		},

		/*初始化表情设置*/
		initEmotion() {
			var that = this;
			var editorTools = {
				emotion: '<div class="emotion" onmousedown="return false" unselectable="on" style="cursor: pointer"></div>'
			};
			var editorObject = {
				bindBody: false,
				options: {
					maxInputNum: 10000
				},
				init: function(selector, options) {
					var self = this;
					self.dom = $(selector);
					self.parentTextAreaDom = $(window.parent.document).find('#' + that.getQueryString('id'));
					self.initBody(self);
					self.initTools(self, options);
					self.initToolsEvents(self);
				},
				initTools: function(self, options) {
					if (!options || !options.tools) return;
					var toolsDom = self.dom.find('.tools');
					toolsDom.attr({
						unselectable: 'on',
						onmousedown: 'return false'
					});
					for (var i in options.tools) {
						var key = options.tools[i];
						toolsDom.append(editorTools[key]);
					}
					var emotion = self.dom.find('.tools .emotion');
					if (emotion.length > 0) {
						var navtools = $('<ul class="nav"></ul>');
						for (let i = 1, j = 0; i + j < 132; i += 10) {
							var li = $('<li></li>');
							for (let j = 0; j < 10 && i + j < 132; j++) {
								var index = i + j;
								var src = 'static/image/editor/emotion/qq/' + (index < 10 ? '00' + index : index < 100 ? '0' + index : index) + '.gif';
								li.append('<img src="' + src + '" onmousedown="return false" unselectable="on" >');
							}
							navtools.append(li);
						}
						emotion.append(navtools);
					}
				},
				initBody: function(self) {
					var bodyDom = self.dom.find('.body').attr('contentEditable', 'true');
					if (!self.bindBody) {
						self.bindBody = true;
						$('body').on('click', function(event) {
							that.stopPropagation(event);
							$(this)
								.find('.nav')
								.fadeOut();
						});
					}

					bodyDom.keyup(function() {
						var html = $(this).html();
						self.parentTextAreaDom.val(html);

						var len = html.length;
						self.dom.find('.bottom .inputInfo .doneNum').text(len);
						var unDoneLength = self.options.maxInputNum - len;
						self.dom.find('.bottom .inputInfo .undoNum').text(unDoneLength);
					});
				},
				initToolsEvents: function(self) {
					self.dom.find('.tools').on('click', '.emotion', function(event) {
						that.stopPropagation(event);
						$(this)
							.find('.nav')
							.show();
					});
					self.dom.find('.tools').on('click', '.emotion .nav img', function(event) {
						that.stopPropagation(event);
						var src = $(this).attr('src');
						var html = '<img src="' + src + '"> ';
						that.insertAtCursor(self.dom.find('.body')[0], html);
						self.dom.find('.body').keyup(); // 触发一下
						self.dom.find('.nav').hide();
					});
				}
			};

			editorObject.init('.webeditor', {
				tools: ['emotion']
			});
		},

		getQueryString(name) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
			var r = window.location.search.substr(1).match(reg);
			if (r != null) return unescape(r[2]);
			return null;
		},

		stopPropagation(event) {
			if (event.stopPropagation) {
				// this code is for Mozilla and Opera
				event.stopPropagation();
			} else if (window.event) {
				// this code is for IE
				window.event.cancelBubble = true;
			}
		},

		insertAtCursor(dom, html) {
			if (dom != document.activeElement) {
				dom.innerHTML = dom.innerHTML + html;
				return;
			}
			var sel, range;
			if (window.getSelection) {
				// IE9 或 非IE浏览器
				sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					range = sel.getRangeAt(0);
					range.deleteContents();
					// Range.createContextualFragment() would be useful here but is
					// non-standard and not supported in all browsers (IE9, for one)
					var el = document.createElement('div');
					el.innerHTML = html;
					var frag = document.createDocumentFragment(),
						node,
						lastNode;
					while ((node = el.firstChild)) {
						lastNode = frag.appendChild(node);
					}
					range.insertNode(frag);
					// Preserve the selection
					if (lastNode) {
						range = range.cloneRange();
						range.setStartAfter(lastNode);
						range.collapse(true);
						sel.removeAllRanges();
						sel.addRange(range);
					}
				}
			} else if (document.selection && document.selection.type != 'Control') {
				// IE < 9
				document.selection.createRange().pasteHTML(html);
			}
		},

		return2Br(str) {
			return str.replace(/\r?\n/g, '<br />');
		},

		showFullImg(src) {
			$('.window-img').find('img')[1].src = src;
			this.showImg = true;
		},

		closeFullImg() {
			this.showImg = false;
		},
		getFormatTime(date) {
			return formatMessageTime(date);
		},
		// 显示时间间隔
		setMsgTimer() {
			let now = Date.now();
			console.log('#### now', now, this.startMsgTime);
			if (now - this.startMsgTime >= 300000) {
				let index = this.messageData.length > 0 ? this.messageData.length - 1 : 0;
				this.messageData[index].showTime = true;
				this.startMsgTime = now;
			}
		},
		sendResource(type, data) {
			let agents = this.sessionMembers.filter(item => item.role === 'agent');
			let role = agents.length > 1 ? 'others' : 'customers';
			return new Promise((resolve, reject) => {
				ivcs.agent.shareResourceWithFileInfo(
					type,
					data,
					role,
					res => resolve(res),
					err => reject(err)
				);
			});
		}
	}
};
</script>

<style scoped lang="less">
@import '../../static/css/gdt-style.css';
@import '../../static/css/im.css';
.zeal-chat {
	.system-msg {
		span {
			padding: 10px;
			background-color: #ebebeb;
			border-radius: 22px;
			color: #777;
		}
	}
}
</style>
